import json
import numpy as np
import matplotlib.pyplot as plt
import platform

# 设置中文字体
system = platform.system()

if system == 'Windows':
    plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows系统使用黑体
elif system == 'Darwin':  # macOS
    plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'PingFang SC', 'Heiti TC']  # macOS系统字体
    
plt.rcParams['axes.unicode_minus'] = False    # 用来正常显示负号

def load_json_data(filename):
    """从JSON文件加载数据"""
    with open(filename, 'r') as f:
        data = json.load(f)
    return data

def plot_signals(t, original, filtered):
    """绘制原始信号和滤波后的信号"""
    fig = plt.figure(figsize=(12, 6))
    
    # 绘制原始信号
    ax1 = plt.subplot(2, 1, 1)
    ax1.plot(t, original)
    ax1.set_title('原始信号', fontsize=12)
    ax1.set_xlabel('时间 (秒)', fontsize=10)
    ax1.set_ylabel('幅度', fontsize=10)
    ax1.grid(True)
    
    # 绘制滤波后的信号
    ax2 = plt.subplot(2, 1, 2)
    ax2.plot(t, filtered)
    ax2.set_title('滤波后的信号', fontsize=12)
    ax2.set_xlabel('时间 (秒)', fontsize=10)
    ax2.set_ylabel('幅度', fontsize=10)
    ax2.grid(True)
    
    plt.tight_layout()
    
    # 定义滚轮事件回调函数
    def on_scroll(event):
        if event.inaxes is None:
            return
        
        # 获取当前坐标轴
        ax = event.inaxes
        # 获取当前y轴范围
        y_min, y_max = ax.get_ylim()
        # 计算缩放范围
        scale = 0.1  # 缩放比例
        if event.button == 'up':
            # 放大
            y_min = y_min + (y_max - y_min) * scale
            y_max = y_max - (y_max - y_min) * scale
        elif event.button == 'down':
            # 缩小
            y_min = y_min - (y_max - y_min) * scale
            y_max = y_max + (y_max - y_min) * scale
        
        # 设置新的y轴范围
        ax.set_ylim(y_min, y_max)
        # 重绘图形
        fig.canvas.draw_idle()
    
    # 绑定滚轮事件
    fig.canvas.mpl_connect('scroll_event', on_scroll)
    
    plt.show()

def main():
    # 加载原始信号数据
    origin_data = load_json_data('origin_data.json')
    sampling_rate = origin_data['sampling_rate']
    original_signal = np.array(origin_data['data'])
    
    # 加载滤波后的信号数据
    filtered_data = load_json_data('filtered_data.json')
    filtered_signal = np.array(filtered_data['data'])
    
    # 生成时间轴
    t = np.arange(len(original_signal)) / sampling_rate
    
    # 绘制信号
    plot_signals(t, original_signal, filtered_signal)
    
    # 打印一些基本信息
    print(f"采样率: {sampling_rate} Hz")
    print(f"数据长度: {len(original_signal)} 点")
    print(f"信号时长: {len(original_signal)/sampling_rate:.2f} 秒")

if __name__ == "__main__":
    main()